const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const SECRET_KEY = 'my_super_secret_2024'
const { verifyToken } = require('../../middilWare/verifyToken')
const {
  createAdmin,
  getAdmin,
  updateAdminPassword,
  updateAdminInfo,
  deleteAdmin,
  getAllAdmins,
  adminLogin,
} = require('../../services/adminService')

// 管理员注册
router.post('/register', async (req, res) => {
  try {
    const admin = await createAdmin(req.body)
    if (admin) {
      res.status(200).json({ code: 200, message: 'admin register success' })
    } else {
      res.status(400).json({ code: 400, message: 'admin register error' })
    }
  } catch (err) {
    res.status(500).json({ code: 500, message: 'register error' })
  }
})

// 管理员登录
router.post('/login', async (req, res) => {
  try {
    const { name, password } = req.body
    const admin = await adminLogin(name, password)
    if (admin) {
      // 生成 token
      const token = jwt.sign(
        { id: admin.id, name: admin.name, role: 'admin' },
        SECRET_KEY,
        { expiresIn: '7d' }
      )
      res
        .status(200)
        .json({
          code: 200,
          message: 'login success',
          admin,
          token,
          juri: admin.juri,
        })
    } else {
      res.status(400).json({ code: 400, message: 'username or password error' })
    }
  } catch (err) {
    res.status(500).json({ code: 500, message: 'login error' })
  }
})

// 获取所有管理员（需token）
router.get('/', verifyToken, async (req, res) => {
  const admins = await getAllAdmins()
  res.json({ code: 200, admins })
})

module.exports = router
